package com.ls.fw.office.poi.excel.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.ddf.EscherClientAnchorRecord;
import org.apache.poi.ddf.EscherRecord;
import org.apache.poi.hssf.record.EscherAggregate;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.WorkbookFactory;

//poi讀取Excel中的圖片
public class ReadExcelPicture {
	public ReadExcelPicture() {
	}

	public Map<Integer, HSSFPictureData> readPicture(String excelPath)
			throws InvalidFormatException, IOException {

		FileInputStream fis = new FileInputStream(excelPath);
		HSSFWorkbook workbook = (HSSFWorkbook) WorkbookFactory.create(fis);
		return readPicture(workbook);
	}

	public Map<Integer, HSSFPictureData> readPicture(HSSFWorkbook workbook)
			throws InvalidFormatException, IOException {
		List<HSSFPictureData> pictures = workbook.getAllPictures();
		// 假設讀取的Excel工作薄中的第一張表
		HSSFSheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
		Map<Integer, HSSFPictureData> map = new HashMap<Integer, HSSFPictureData>();
		HSSFPicture picture = null;
		for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
			HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
			int rowIndex = anchor.getRow1();
			if (shape instanceof HSSFPicture) {
				int rowmark = rowIndex;
				picture = (HSSFPicture) shape;
				int pictureIndex = picture.getPictureIndex() - 1;
				map.put(rowmark, pictures.get(pictureIndex));
			}
		}
		return map;
	}
	
	public static List<MyPictureData> getAllPictures(String excelPath)
	throws InvalidFormatException, IOException {

		FileInputStream fis = new FileInputStream(excelPath);
		HSSFWorkbook workbook = (HSSFWorkbook) WorkbookFactory.create(fis);
		return getAllPictures(workbook);
	}

	public static List<MyPictureData> getAllPictures(HSSFWorkbook workbook) {
        List<MyPictureData> list = new ArrayList<MyPictureData>();
 
        List<HSSFPictureData> pictureList = workbook.getAllPictures();
        List<ClientAnchorInfo> clientAnchorRecords = getClientAnchorRecords(workbook);
         
        if (pictureList.size() != clientAnchorRecords.size()) {
            throw new RuntimeException("解析文件中的图片信息出错，找到的图片数量和图片位置信息数量不匹配");
        }
         
        for (int i = 0; i < pictureList.size(); i++) {
            HSSFPictureData pictureData = pictureList.get(i);
            ClientAnchorInfo anchor = clientAnchorRecords.get(i);
            HSSFSheet sheet = anchor.sheet;
            EscherClientAnchorRecord clientAnchorRecord = anchor.clientAnchorRecord;
            list.add(new MyPictureData(workbook, sheet, pictureData, clientAnchorRecord));
        }
         
        return list ;
    }
 
    private static class ClientAnchorInfo {
        public HSSFSheet sheet;
        public EscherClientAnchorRecord clientAnchorRecord;
         
        public ClientAnchorInfo(HSSFSheet sheet, EscherClientAnchorRecord clientAnchorRecord) {
            super();
            this.sheet = sheet;
            this.clientAnchorRecord = clientAnchorRecord;
        }
    }
    private static List<ClientAnchorInfo> getClientAnchorRecords(HSSFWorkbook workbook) {
        List<ClientAnchorInfo> list = new ArrayList<ClientAnchorInfo>();
         
        EscherAggregate drawingAggregate = null;
        HSSFSheet sheet = null;
        List<EscherRecord> recordList = null;
        Iterator<EscherRecord> recordIter = null;
        int numSheets = workbook.getNumberOfSheets();
        for(int i = 0; i < numSheets; i++) {
            sheet = workbook.getSheetAt(i);
            drawingAggregate = sheet.getDrawingEscherAggregate();
            if(drawingAggregate != null) {
                recordList = drawingAggregate.getEscherRecords();
                recordIter = recordList.iterator();
                while(recordIter.hasNext()) {
                    getClientAnchorRecords(sheet, recordIter.next(), 1, list);
                }
            }
        }
         
        return list;
    }
 
    private static void getClientAnchorRecords(HSSFSheet sheet, EscherRecord escherRecord, int level, List<ClientAnchorInfo> list) {
        List<EscherRecord> recordList = null;
        Iterator<EscherRecord> recordIter = null;
        EscherRecord childRecord = null;
        recordList = escherRecord.getChildRecords();
        recordIter = recordList.iterator();
        while(recordIter.hasNext()) {
            childRecord = recordIter.next();
            if(childRecord instanceof EscherClientAnchorRecord) {
                ClientAnchorInfo e = new ClientAnchorInfo(sheet, (EscherClientAnchorRecord) childRecord);
                list.add(e);
            }
            if(childRecord.getChildRecords().size() > 0) {
                getClientAnchorRecords(sheet, childRecord, level+1, list);
            }
        }
    }
	public static void main(String args[]) throws Exception,
			IOException {

		String excelPath = "D:\\case\\茂名取款嫌疑人3号-0.26.xls";
		String savePicturePath = "D:\\case\\images\\";
		File file = new File(savePicturePath);
		if(!file.exists()){
			file.mkdirs();
		}
		ReadExcelPicture readExcelPicture = new ReadExcelPicture();
		/*Map<Integer, HSSFPictureData> map = readExcelPicture
				.readPicture(excelPath);
		// 傳入一個你需要的Excel圖片行索引，必須確保該Excel行索引中有圖片，
		// 而且是在已經讀取的Excel行索引范圍內，我傳入的是1
		for (Integer index : map.keySet()) {
			HSSFPictureData pictureData = map.get(index);
			// 獲取包含圖片格式的文件字符串
			String ext = pictureData.suggestFileExtension();
			// 代表圖片信息的字節數據
			byte[] data = pictureData.getData();
			// 根據圖片格式將圖片寫出到磁盤
			FileOutputStream out = new FileOutputStream(savePicturePath
					+ "a"+index+"."+ext);
			out.write(data);
			out.close();
		}*/
		//dd(excelPath,savePicturePath);
	}
	
	public static void dd(String excelPath,String savePicturePath) throws Exception, IOException{
		List<MyPictureData> list = ReadExcelPicture.getAllPictures(excelPath);
		int index = 0;
		for (MyPictureData myPictureData : list) {
			HSSFPictureData pictureData = myPictureData.getPictureData();
			String ext = pictureData.suggestFileExtension();
			// 代表圖片信息的字節數據
			byte[] data = pictureData.getData();
			// 根據圖片格式將圖片寫出到磁盤
			FileOutputStream out = new FileOutputStream(savePicturePath
					+ "b"+(index++)+"."+ext);
			out.write(data);
			out.close();
			//System.out.println(myPictureData.getClientAnchor().toString());
			System.out.print("图片"+index+":");
			System.out.print("("+myPictureData.getRow1()+":"+myPictureData.getCol1()+")");
			System.out.print(","+"("+myPictureData.getRow2()+":"+myPictureData.getCol2()+")");
			System.out.print("---");
			int i = 0;
			System.out.print(myPictureData.getSheet().getRow(myPictureData.getRow1()).getCell(myPictureData.getCol1()-1).getStringCellValue());
			if(index!=1){
				while(i<6){
					System.out.print(","+myPictureData.getSheet().getRow(myPictureData.getRow1()).getCell(myPictureData.getCol1()+1+i).getStringCellValue());
					i++;
				}
			}
			System.out.println();
		}
	}
}